package com.kaikai.edu.controller.front;

import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kaikai.commonutils.JwtUtils;
import com.kaikai.commonutils.R;
import com.kaikai.edu.client.UcenterClient;
import com.kaikai.edu.entity.EduComment;
import com.kaikai.edu.service.EduCommentService;
import com.kaikai.servicebase.exceptionhandler.MyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import vo.CommentUserInfo;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("eduservice/comment")
public class CommentFrontController {
    @Autowired
    private UcenterClient ucenterClient;
    @Autowired
    private EduCommentService commentService;


//    //根据课程id分页获取评论列表
    @GetMapping("{page}/{limit}")
    public R index(@PathVariable Long page,
                   @PathVariable Long limit,
                    String courseId)
    {
        Page<EduComment> pageParam=new Page<>(page,limit);
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("course_id", courseId);
        commentService.page(pageParam,wrapper);
        List<EduComment> commentList = pageParam.getRecords();
        Map<String, Object> map = new HashMap<>();
        map.put("items", commentList);
        map.put("current", pageParam.getCurrent());
        map.put("pages", pageParam.getPages());
        map.put("size", pageParam.getSize());
        map.put("total", pageParam.getTotal());
        map.put("hasNext", pageParam.hasNext());
        map.put("hasPrevious", pageParam.hasPrevious());
        return R.ok().data(map).data("commentList",commentList);
    }
    //根据课程id添加评论
    @PostMapping("save")
    public R save(@RequestBody EduComment comment, HttpServletRequest request){

       String memberId= JwtUtils.getMemberIdByJwtToken(request);
       if(StringUtils.isEmpty(memberId)){
           throw new MyException(20001,"请先登录");
       }

        comment.setMemberId(memberId);
       //获得用户信息
        CommentUserInfo userInfo = ucenterClient.getUserInfo(memberId);
        comment.setAvatar(userInfo.getAvatar());
        comment.setNickname(userInfo.getNickname());
        commentService.save(comment);


        /**获得用户信息
         *     @ApiModelProperty(value = "会员id")
         *     private String memberId;
         *     @ApiModelProperty(value = "会员昵称")
         *     private String nickname;
         *     @ApiModelProperty(value = "会员头像")
         */
        return R.ok();
    }

}
